package com.cml.common.util;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * 姓名：陈茂林
 * 时间：2023/11/10 8:51
 * 描述：
 */
public class SocketChannelParseStringUtil {
    public  static  String parse(SocketChannel socketChannel) throws IOException {
        ByteBuffer messageLength = ByteBuffer.allocate(4);
        socketChannel.read(messageLength );
        messageLength.flip();

        ByteBuffer message = ByteBuffer.allocate(messageLength.getInt());
        socketChannel.read(message );
        message.flip();
        byte[] messageByte = new byte[message.capacity()];
        message.get(messageByte);
        return new String(messageByte);
    }

    public static void stringDataBuild(ByteBuffer byteBuffer,String data){
        byteBuffer.putInt(data.length());
        byteBuffer.put(data.getBytes());
    }
}
